<template>
  <div class="container">
    <!-- <h1>测试 密码加密&参数签名</h1>
    <p>生成(pwd)：{{ pwd }}</p>
    <p>对比(pwd)：475406ACEA705229FE9129C0438D9A33</p>

    <p>生成(key)：{{ key }}</p>
    <p>对比(key)：C8539D688434DB73577E49F74936F40D</p> -->

    <p>sessionToken：{{sessionToken}}</p>
    <LoginView
      v-if="!userInfo || userInfo.sessionToken === undefined || userInfo.sessionToken === '0'"
      :params.sync="loginForm"
      :userInfo="userInfo"
      :init="init"
      :sendCode="sendVerifyCode"
      :verifyCode="(code) => (verifyUpdateDeviceForm.code = code, verifyUpdateDevice())"
      @submit="submit"
    />
    <template v-else>
      <a href="javascript:;" @click="logout">注销登录</a>
      <ClubList
        :deviceId="deviceId"
        :sessionToken="sessionToken"
        :userId="userInfo && userInfo.user && userInfo.user.userId"
      />
    </template>

    <CardView
      title="获取公钥"
      :params.sync="rasPubKeyForm"
      :body="rasPubKeyData"
    >
      <template #btns>
        <button @click="init">Init</button>
      </template>
    </CardView>

    <CardView title="登录" :params.sync="loginForm" :body="userInfo">
      <template #btns>
        <button @click="submit">Phone Login</button>
      </template>
    </CardView>

    <CardView
      v-if="userInfo && userInfo.sessionToken == 0"
      title="新的设备需要验证手机号"
      :params.sync="sendVerifyCodeForm"
      :body="sendVerifyCodeData"
    >
      <template #btns>
        <button @click="sendVerifyCode">sendVerifyCode</button>
      </template>
    </CardView>

    <CardView
      v-if="userInfo && userInfo.sessionToken == 0 && sendVerifyCodeData"
      title="提交验证码（新的设备）"
      :params.sync="verifyUpdateDeviceForm"
      :body="verifyUpdateDeviceData"
    >
      <template #btns>
        <button @click="verifyUpdateDevice">verifyUpdateDevice</button>
      </template>
    </CardView>

    <CardView
      title="获取联机用户"
      :params.sync="onlineUserForm"
      :body="onlineUsers"
    >
      <template #btns>
        <button @click="getMiniGameOnlineUsers">getMiniGameOnlineUsers</button>
      </template>
    </CardView>

    <CardView
      title="获取俱乐部列表"
      :params.sync="clubListForm"
      :body="clubList"
    >
      <template #btns>
        <button @click="getClubList">getClubList</button>
      </template>
    </CardView>

    <CardView
      title="获取房间历史记录"
      :params.sync="roomHistoryForm"
      :body="roomHistoryData"
    >
      <template #btns>
        <button @click="getRoomHistory">getRoomHistory</button>
      </template>
    </CardView>

    <CardView
      title="获取房间详情"
      :params.sync="roomDetailForm"
      :body="roomDetailData"
    >
      <template #btns>
        <button @click="getRoomDetail">getRoomDetail</button>
      </template>
    </CardView>
  </div>
</template>

<script>
import {getUserRASPubKey, phoneLogin, sendVerifyCode, verifyUpdateDevice, getMiniGameOnlineUsers, getClubList, getRoomHistory, getRoomDetail} from '@/api/demo';
import {getParamsSign, getMd5Password, randomStr} from '@/utils/util';
import { encrypt, decrypt} from '@/utils/jsencrypt.v2';

import CardView from '@/components/demo/card-view.vue';
import LoginView from '@/components/demo/login.vue';
import ClubList from '@/components/demo/club-list.vue';
import forge from 'node-forge';

const DeviceId = localStorage.getItem('DeviceId') || randomStr(); // 设备号

export default {
  name: 'App',
  components: {
    CardView,
    LoginView,
    ClubList
  },
  data() {
    return {
      deviceId: DeviceId,
      sessionToken: '',
      pwd: getMd5Password('hahababy@123'),
      key: getParamsSign({
        userId: '56142866',
        clubId: '7112239',
        pageNo: '1',
        playType: '0,1,2',
        personNum: '2,3,4,5,6,7,8,9',
        minGrade: '0',
        maxGrade: '1000',
        sessionToken: 'cGfJ511',
        version: '5.7.29.6',
        lang: 'cn',
        deviceType: '1',
        deviceId: 'f50db884b65846f4ce7c25ff63e22e89',
        idfa: 0,
        platform: 'h5',
        channel: 0
      }),
      rasPubKeyForm: {
        version: '5.7.29.6',
        lang: 'cn',
        deviceId: DeviceId,
        idfa: 0,
        platform: 'h5',
        channel: 0,
      },
      rasPubKeyData: '',
      loginForm: {
        time: new Date().getTime(),
        lang: 'cn',
        countryCode: '+86',
        phoneNum: '',
        password: '',
        isSimulator: 'false',
        aesKey: '',
        rsaKey: '',
        isAutoLogin: 'true',
        deviceVersion: '',
        phoneModel: 'chrome',
        networkOper: '',
        appVersionCode: '100000',
        version: '5.7.29.6',
        signVersion: '',
        packageName: '',
        deviceType: '1',
        uSign: '',
        idfa: 0,
        platform: 'h5',
        channel: 0,
        deviceId: DeviceId,
      },
      userInfo: {},
      sendVerifyCodeForm: {
        updateType: 1,
        countryCode: '+86',
        phoneNum: '',
        userId: '',
        sessionToken: 0,
        version: '5.7.30.5',
        lang: 'cn',
        deviceType: 1,
        deviceId: DeviceId,
        idfa: 0,
        platform: 'h5',
        channel: 0,
      },
      sendVerifyCodeData: '',
      verifyUpdateDeviceForm: {
        updateType: 1,
        code: '',
        deviceId: DeviceId,
        idfa: 0,
        deviceVersion: '',
        isSimulator: false,
        phoneModel: 'chrome',
        networkOper: '',
        appVersionCode: 100000,
        version: '5.7.30.5',
        signVersion: '',
        packageName: '',
        deviceType: 1,
        userId: '',
        sessionToken: 0,
        lang: 'cn',
        platform: 'h5',
        channel: 0,
      },
      verifyUpdateDeviceData: '',
      onlineUserForm: {
        userId: '',
        sessionToken: '',
        version: '5.7.30.5',
        lang: 'cn',
        deviceType: 1,
        deviceId: DeviceId,
        idfa: 0,
        platform: 'h5',
        channel: 0,
      },
      onlineUsers: '',
      clubListForm: {
        userId: '',
        sessionToken: '',
        version: '5.7.30.5',
        lang: 'cn',
        deviceType: 1,
        deviceId: DeviceId,
        idfa: 0,
        platform: 'h5',
        channel: 0,
        bShowApplying: 1,
      },
      clubList: '',
      roomHistoryForm: {
        userId: '',
        sessionToken: '',
        clubId: '',
        pageNo: '',
        playType: '',
        personNum: '',
        minGrade: '',
        maxGrade: '',
      },
      roomHistoryData: '',
      roomDetailForm: {
        userId: '',
        sessionToken: '',
        roomId: '',
        playType: '',
      },
      roomDetailData: '',
    }
  },
  mounted() {
    // this.init();
    const user = localStorage.getItem('userInfo');
    const rasPubKeyData = localStorage.getItem('rasPubKeyData');
    this.sessionToken = localStorage.getItem('sessionToken');
    if (user) {
      try {
        this.userInfo = JSON.parse(user);
        this.setUserKey('verifyUpdateDeviceForm');
        this.setUserKey('onlineUserForm');
        this.setUserKey('clubListForm');
        this.setUserKey('roomHistoryForm');
        this.setUserKey('roomDetailForm');
      } catch (error) {
        console.warn(error);
      }
    }

    if (rasPubKeyData) {
      try {
        this.rasPubKeyData = JSON.parse(rasPubKeyData);
        this.publicKey = this.rasPubKeyData.data;
      } catch (error) {
        console.warn(error);
      }
    }
  },
  methods: {
    logout() {
      this.sessionToken = '';
      this.rasPubKeyData = '';
      this.publicKey = '';
      this.privateKey = '';
      this.userInfo = {};
      localStorage.removeItem('userInfo');
      localStorage.removeItem('rasPubKeyData');
      localStorage.removeItem('sessionToken');
    },
    generateRsaKey() {
      // 创建一个新的RSA密钥对
      const pair = forge.pki.rsa.generateKeyPair({
        bits: 512, // 指定密钥长度
        e: 0x10001 // 公钥指数
      });

      // 获取公钥
      const publicKey = forge.pki.publicKeyToPem(pair.publicKey);
      // 获取私钥
      const privateKey = forge.pki.privateKeyToPem(pair.privateKey);
      return [publicKey, privateKey];
    },
    setUserKey(key) {
      this[key].userId = this.userInfo.user.userId;
      this[key].sessionToken = this.sessionToken || this.userInfo.sessionToken;
    },

    async init() {
      try {
        const data = this.rasPubKeyForm;
        const res = await getUserRASPubKey({
          ...data,
          sign: getParamsSign(data)
        });
        this.rasPubKeyData = res.data;
        this.publicKey = (res.data.data);

        this.loginForm.aesKey = encrypt(randomStr(6), this.publicKey);
        const [publicKey, privateKey] = this.generateRsaKey();
        this.loginForm.rsaKey = publicKey.replace(/-----BEGIN PUBLIC KEY-----/, "").replace(/-----END PUBLIC KEY-----/, "").replace(/\n/g, "").replace(/\r/g, "");
        this.privateKey = privateKey.replace(/-----BEGIN RSA PRIVATE KEY-----/, "").replace(/-----END RSA PRIVATE KEY-----/, "").replace(/\n/g, "").replace(/\r/g, "");

        localStorage.setItem('rasPubKeyData', JSON.stringify(this.rasPubKeyData));
        localStorage.setItem('DeviceId', data.deviceId); // 存储设备号
      } catch (error) {
        console.warn('获取公钥失败', error);
      }
    },
    submit() {
      let d = this.loginForm;
      const data = {
        ...d,
        password: getMd5Password(d.password),
        phoneNum: encrypt(d.phoneNum, this.publicKey)
      };
      data['sign'] = getParamsSign(data)

      phoneLogin(data).then((res) => {
        if (res.data.errorCode === 0) {
          this.userInfo = res.data;
          this.sessionToken = decrypt(res.data.sessionToken, this.privateKey);

          localStorage.setItem('sessionToken', this.sessionToken);
          localStorage.setItem('userInfo', JSON.stringify(res.data));

          this.setUserKey('verifyUpdateDeviceForm');
          this.setUserKey('onlineUserForm');
          this.setUserKey('clubListForm');
          this.setUserKey('roomHistoryForm');
          this.setUserKey('roomDetailForm');

          if (this.userInfo.sessionToken == 0) {
            let d = this.sendVerifyCodeForm;
            d.userId = this.userInfo.user.userId;
            d.phoneNum = this.userInfo.userSecurityInfo.phoneNum;
            d.countryCode = this.userInfo.userSecurityInfo.countryCode;
          } else {
            alert(res.data && res.data.errorCode === 0 ? '登录成功' : '登录失败');
          }
        }
      });
    },
    sendVerifyCode() {
      let data = this.sendVerifyCodeForm;
      delete data.sign;
      data['sign'] = getParamsSign(data)
      sendVerifyCode(data).then((res) => {
        this.sendVerifyCodeData = res.data;
        alert(res.data && res.data.errorCode === 0 ? '发送成功' : '发送失败');
      })
    },
    verifyUpdateDevice() {
      this.setUserKey('verifyUpdateDeviceForm');
      let data = this.verifyUpdateDeviceForm;
      delete data.sign;
      data['sign'] = getParamsSign(data)
      verifyUpdateDevice(data).then((res) => {
        this.verifyUpdateDeviceData = res.data;
        if (res.data.data && res.data.data.token) {
          this.userInfo.sessionToken = res.data.data.token;
          this.sessionToken = decrypt(res.data.data.token, this.privateKey);
          this.setUserKey('onlineUserForm');
          this.setUserKey('clubListForm');
          this.setUserKey('roomHistoryForm');
          this.setUserKey('roomDetailForm');
          alert('登录成功');
        } else {
          alert(res.data.errMsg);
        }
      })
    },
    getMiniGameOnlineUsers() {
      this.setUserKey('onlineUserForm');
      const data = this.onlineUserForm;
      delete data.sign;
      data['sign'] = getParamsSign(data)
      getMiniGameOnlineUsers(data).then((res) => {
        this.onlineUsers = res.data;
      })
    },
    getClubList() {
      this.setUserKey('clubListForm');
      let data = this.clubListForm;
      delete data.sign;
      data['sign'] = getParamsSign(data)
      getClubList(data).then((res) => {
        this.clubList = res.data;
      })
    },
    getRoomHistory() {
      this.setUserKey('roomHistoryForm');
      let data = this.roomHistoryForm;
      delete data.sign;
      data['sign'] = getParamsSign(data)
      getRoomHistory(data).then((res) => {
        this.roomHistoryData = res.data;
      })
    },
    getRoomDetail() {
      this.setUserKey('roomDetailForm');
      let data = this.roomDetailForm;
      delete data.sign;
      data['sign'] = getParamsSign(data)
      getRoomDetail(data).then((res) => {
        this.roomDetailData = res.data;
      })
    },
  }
}
</script>

<style scoped>
.container {
  padding: 10px;
  overflow: hidden;
}
.container a {
  color: blue;
}
</style>
